<?php
/*
 * @Date: 2022-09-28 22:52:03
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2024-05-13 20:21:56
 */
namespace Ldy;

class Install
{
    const WEBMAN_PLUGIN = true;

    /**
     * @var array
     */
    protected static $pathRelation = array (
        'config/plugin/ldy/admin' => 'config/plugin/ldy/admin',
        'config/plugin/casbin/webman-permission/permission.php'=>'config/plugin/casbin/webman-permission/permission.php',
        'config/plugin/casbin/webman-permission/rbac-model.conf'=>'config/plugin/casbin/webman-permission/rbac-model.conf',
        'config/bootstrap.php'=>'config/bootstrap.php',
        'config/redis.php' => 'config/redis.php',
        'config/thinkcache.php' => 'config/thinkcache.php',
        'config/thinkorm.php' => 'config/thinkorm.php',
        'config/container.php' => 'config/container.php',
        '.env.example' => '.env',
        'websocket/WebsocketEven.php'=> 'process/WebsocketEven.php'
    );

    /**
     * 卸载时不删除文件
     *
     * @var array
     */
    protected static $noDelFile = array(
        'config/bootstrap.php',
        'config/redis.php',
        '.env.example',
        'config/container.php'
    );

    /**
     * 不覆盖复制，只有文件不存在复制
     *
     * @var array
     */
    protected static $notOverWrite = array(
        '.env.example',
        'config/plugin/ldy/admin',
        'websocket/WebsocketEven.php'
    );

    /**
     * Install
     * @return void
     */
    public static function install()
    {
        static::installByRelation();
    }

    /**
     * Uninstall
     * @return void
     */
    public static function uninstall()
    {
        self::uninstallByRelation();
    }

    /**
     * installByRelation
     * @return void
     */
    public static function installByRelation()
    {
        foreach (static::$pathRelation as $source => $dest) {
            if ($pos = strrpos($dest, '/')) {
                $parent_dir = base_path().'/'.substr($dest, 0, $pos);
                if (!is_dir($parent_dir)) {
                    mkdir($parent_dir, 0777, true);
                }
            }

            $overWrite = true;
            if(in_array($source, self::$notOverWrite)) $overWrite = false;
            //symlink(__DIR__ . "/$source", base_path()."/$dest");
            copy_dir(__DIR__ . "/$source", base_path()."/$dest", $overWrite);
            echo "Create $dest".PHP_EOL;
        }
    }

    /**
     * uninstallByRelation
     * @return void
     */
    public static function uninstallByRelation()
    {
        foreach (static::$pathRelation as $source => $dest) {
            if(in_array($source, self::$noDelFile)) continue;
            $path = base_path()."/$dest";
            if (!is_dir($path) && !is_file($path)) {
                continue;
            }
            echo "Remove $dest";
            if (is_file($path) || is_link($path)) {
                unlink($path);
                continue;
            }
            remove_dir($path);
        }
    }
    
}